<?php

/**
 * SigmaCMS - Content Management System
 *
 * Copyright (C) 2008 Pavol Biely
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 * @package    SigmaCMS
 * @author     Pavol Biely <pavolbiely@gmail.com>
 * @copyright  2008 Pavol Biely
 * @license    http://www.gnu.org/licenses/gpl.txt   GNU General Public License
 * @link       http://pabi3.com/
 * @since      0.1.0
 */

final class DB_ExtendSqlite
{
	/**
	 * Initialization
	 *
	 * @return void
	 */
	static public function initialize($connection)
	{
		// Unix time
		sqlite_create_function($connection,'UNIX_TIMESTAMP','strtotime',1);

		// current time
		sqlite_create_function($connection,'NOW','time',0);

		// SUBSTR
		sqlite_create_function($connection,'SUBSTRING','substr',3);

		// day in month
		sqlite_create_function($connection,'DAY',self::getCallback('callback_day'),1);
		sqlite_create_function($connection,'DAYOFMONTH',self::getCallback('callback_day'),1);

		// month
		sqlite_create_function($connection,'MONTH',self::getCallback('callback_month'),1);

		// year
		sqlite_create_function($connection,'YEAR',self::getCallback('callback_year'),1);
	}

	/**
	 * Emulate unsupported queries
	 *
	 * @return void
	 */
	static public function cleanQuery(&$sql)
	{
		// emulate MySQL command SHOW TABLES
		if (preg_match('/^SHOW\s+TABLES$/',trim($sql))) {
			$sql = "SELECT name FROM sqlite_master WHERE type='table'";
			return;
		}

		// remove character `
		$sql = preg_replace('/`(\w+)`/','$1',$sql);

		// UPDATE and DELETE does not support LIMIT, so it will be removed
		/*if (preg_match('/^(UPDATE|DELETE)(.*)LIMIT\s+([0-9]+)$/',$sql,$match)) {
			$sql = $match[1].$match[2];
		}*/
	}

	/**
	 * Create callback for methods of this class
	 *
	 * @param string $callback
	 * @return callback
	 */
	static private function getCallback($callback)
	{
		return array(new DB_ExtendSqlite,$callback);
	}

	/**
	 * Current day in month
	 *
	 * @param integer $time
	 * @return callback
	 */
	private function callback_day($time)
	{
		return date('d',strtotime($time));
	}

	/**
	 * Month
	 *
	 * @param integer $time
	 * @return callback
	 */
	private function callback_month($time)
	{
		return date('m',strtotime($time));
	}

	/**
	 * Year
	 *
	 * @param integer $time
	 * @return callback
	 */
	private function callback_year($time)
	{
		return date('y',strtotime($time));
	}
}
